package com.learn.singleton;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Emperor2 {
    // 定义系统中能产生的实例数量
    private static final int maxNumberOfEmperor = 2;
    // 定义每个对象的名称
    private static final List<String> nameList = new ArrayList<>();
    // 存储每个对象
    private static final List<Emperor2> emperor2List = new ArrayList<>();
    // 当前对象的序号
    private static int countNumberOfEmperor = 0;

    // 初始化的时候先创建所有的对象
    static {
        for (int i = 0; i < maxNumberOfEmperor; i++) {
            emperor2List.add(new Emperor2("皇" + (i+1) + "帝"));
        }
    }

    private Emperor2() {

    }

    private Emperor2(String name) {
        nameList.add(name);
    }

    // 随机返回一个对象
    public static Emperor2 getInstance() {
        Random random = new Random();
        countNumberOfEmperor = random.nextInt(maxNumberOfEmperor);
        return emperor2List.get(countNumberOfEmperor);
    }

    // 对象的其他方法
    public void say() {
        System.out.println(nameList.get(countNumberOfEmperor));
    }
}
